//
//  NetWorkTools.swift
//  NetworkTools
//
//  Created by 孙英建 on 16/4/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

enum ResquestMethod: Int{
    case GET = 0
    case POST = 1
}

class NetWorkTools: AFHTTPSessionManager {
    
    
    // 单例
    static let sharedTools: NetWorkTools = {
       
        let tools = NetWorkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    // 网络请求方法
    func request(method: ResquestMethod, urlString: String, paramaters: AnyObject?, callBack:(response: AnyObject?, error: NSError?) -> ()){
        
        if method == ResquestMethod.GET { // GET
            self.GET(urlString, parameters: paramaters, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                  callBack(response: nil, error: error)
            })
        }else{ // POST
            self.POST(urlString, parameters: paramaters, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
        }
    }
}

// MARK: - 请求微博首页的数据
extension NetWorkTools {
    
    func loadData(access_token: String, since_id: Int64, max_id: Int64, callBack: (response: AnyObject?, error: NSError?) -> ()){
        
        // 请求url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = [
            "access_token": access_token,
            "since_id": "\(since_id)",
            "max_id": "\(max_id)"
        ]
        
        // 请求
        request(ResquestMethod.GET, urlString: urlString, paramaters: params) { (response, error) -> () in
            callBack(response: response, error: error)
        }
        
    }
    
}












